package agent.impl;

import interfaces.Subscriber;

import java.util.Vector;

import operations.Operation;
import server.RemoteDomaineManager;
import server.impl.ClientRemoteImpl;
import topic.Topic;
import data.DataObject;
import agent.AgentDCS;

public class AgentDCSImpl implements AgentDCS {
	private Vector<RemoteDomaineManager> remoteDomaines = null;

	public AgentDCSImpl() {
		remoteDomaines = new Vector<RemoteDomaineManager>();
	}

	public void broadcast() {
		// TODO Auto-generated method stub

	}

	public void registerRemoteListener(RemoteDomaineManager remoteDomaine) {
		remoteDomaines.add(remoteDomaine);
	}

	public DataObject getDataObject(String parentTopicName, String topicName) {
		Topic topic;
		try{
		for (int i = 0; i < remoteDomaines.size(); i++) {
			topic = remoteDomaines.get(i).getTopic(parentTopicName, topicName);
			if(topic!=null)
				return topic.getDataObject();
		}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public Topic createTopic(String parentTopicName, Operation operation) {
		Subscriber[] subscriber = null;
		int posRemote = -1;

		for (int i = 0; i < remoteDomaines.size(); i++) {
			subscriber = remoteDomaines.get(i).getTopicsSuscribers(
					parentTopicName);
			if (subscriber != null) {
				posRemote = i;
				i = remoteDomaines.size() + 1;
			}
		}
		if (subscriber == null)
			return null;
		ClientRemoteImpl client = new ClientRemoteImpl();
		client.createPublisher(subscriber[0]);
		client.buildDataWriter(null);
		client.writeOperation(parentTopicName, operation);

		return remoteDomaines.get(posRemote).getTopic(parentTopicName,
				operation.getData().getData().extract_Value().toString());
	}

}
